<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
namespace app\api\validate\wddj\user;

use think\Validate;

class UserRealNameAuthentication extends Validate
{
    /**
     * 验证规则
     */
    protected $rule = [
        'name'=>'require',
        'id_card'=>'require|checkIdCard',
    ];
    /**
     * 提示消息
     */
    protected $message = [
        'name.require'=>'请输入姓名',
        'id_card.require'=>'请输入身份证号',
    ];

    protected function checkIdCard($value, $rule, $data)
    {
        // 基本格式验证
        $id_card_pattern = '/^\d{17}[0-9xX]$/';
        if (!preg_match($id_card_pattern, $value)) {
            return "身份证号码格式不正确！";
        }

        // 省份代码验证
        $province_code = substr($value, 0, 2);
        $valid_province_codes = [
            '11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82'
        ];
        if (!in_array($province_code, $valid_province_codes)) {
            return "身份证号码中的省份代码不正确！";
        }

        // 生日验证
        $year = substr($value, 6, 4);
        $month = substr($value, 10, 2);
        $day = substr($value, 12, 2);
        if (!checkdate($month, $day, $year)) {
            return "身份证号码中的出生日期不正确！";
        }

        // 校验码验证
        $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        $verify_codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            $sum += intval($value[$i]) * $factor[$i];
        }
        $verify_code = $verify_codes[$sum % 11];
        if (strtoupper($value[17]) != $verify_code) {
            return "身份证号码校验码不正确！";
        }

        return true;
    }
    
}
